package com.xnet.shiro.controller.base;

import com.alibaba.fastjson.JSONObject;
import com.xnet.common.controller.AbstractController;
import com.xnet.common.entity.*;
import com.xnet.common.utils.JSONUtils;
import com.xnet.common.utils.TreeGridJson;
import com.xnet.common.utils.TreeNodeUtils;
import com.xnet.shiro.entity.base.DepartmentEntity;
import com.xnet.shiro.entity.base.OrganizeEntity;
import com.xnet.shiro.service.base.DepartmentService;
import com.xnet.shiro.service.base.OrganizeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.xnet.common.annotation.SysLog;

/**
 * 部门控制器
 *
 * @author Xingyc
 * @date 2018-1-11 14:50:01
 */
@RestController
@RequestMapping("/basemanage/department")
public class DepartmentController extends AbstractController {


    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private OrganizeService organizeService;


    /**
     * 获取部门树
     *
     * @param organizeId
     * @param keyword
     * @return
     */
    @RequestMapping("/getTreelist")
    public List<TreeEntity> treelist(String organizeId, String keyword) {

        List<DepartmentEntity> allList = departmentService.getListTree(organizeId, null);
        List<DepartmentEntity> filterList = new ArrayList<>();

        if (keyword != null && !keyword.isEmpty()) {
            filterList = allList.stream().filter(x -> x.getFullName().contains(keyword)).collect(Collectors.toList());
        } else {
            filterList = allList;
        }

        List<TreeEntity> treeList = convertToTreeList(filterList);
        List<TreeEntity> relationTreeList = new ArrayList<>();
        if (keyword != null && !keyword.isEmpty()) {
            List<TreeEntity> allTreeList = convertToTreeList(allList);//获取所有符合条件的树形列表
            TreeNodeUtils.getWholeTreeChain(allTreeList, treeList, relationTreeList);//获取符合过滤条件的所有节点链条
        } else {
            relationTreeList = treeList;
        }
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(relationTreeList, "0", newTreeList);
        return newTreeList;
    }

    /**
     * 转换实体为树形结构
     *
     * @param itemList
     * @return
     */
    private List<TreeEntity> convertToTreeList(List<DepartmentEntity> itemList) {

        List<TreeEntity> treeList = new ArrayList<>();
        for (DepartmentEntity item : itemList) {
            TreeEntity tree = new TreeEntity();
            boolean hasChildren = itemList.stream().filter(x -> x.getParentId().equals(item.getDepartmentId())).count() > 0;
            tree.setId(item.getDepartmentId());
            tree.setText(item.getFullName());
            tree.setValue(item.getDepartmentId());
            tree.setIsExpand(true);
            tree.setComplete(true);
            tree.setHasChildren(hasChildren);
            tree.setParentId(item.getParentId());
            treeList.add(tree);
        }
        return treeList;
    }


    /**
     * 获取机构+部门树
     *
     * @param keyword
     * @return
     */
    @RequestMapping("/getOrgDeptTree")
    public List<TreeEntity> getOrganizeDepartmentTreelist(String keyword) {

        //获取所有机构列表
        List<OrganizeEntity> allOrgList = organizeService.getListTree(null);

        //获取所有部门列表
        List<DepartmentEntity> allDeptList = departmentService.getListTree(null, null);

        //组合机构+部门 并转换为树形实体列表
        List<TreeEntity> allOrgDeptTreeList = departmentService.convertOrganizeToTreeList(allOrgList, allDeptList,true);

        //获取关联追溯后的树形列表
        List<TreeEntity> relationTreeList = new ArrayList<>();

        if (keyword != null && !keyword.isEmpty()) {
            //执行检索过滤 获取过滤后的树形列表
            List<TreeEntity> filterTreeList = new ArrayList<>();
            filterTreeList = allOrgDeptTreeList.stream().filter(x -> x.getText().contains(keyword)).collect(Collectors.toList());
            //获取符合过滤条件的所有节点链条（向上追溯）
            TreeNodeUtils.getWholeTreeChain(allOrgDeptTreeList, filterTreeList, relationTreeList);

        } else {
            relationTreeList = allOrgDeptTreeList;
        }

        //创建结果列表
        List<TreeEntity> newTreeList = new ArrayList<>();
        TreeNodeUtils.convertToTree(relationTreeList, "0", newTreeList);
        return newTreeList;
    }


    @RequestMapping("/getTreeListJson")
    public Object getTreeListJson() {

        List<OrganizeEntity> organizeEntities= organizeService.list();
        List<DepartmentEntity> departmentEntities=departmentService.listDepartment(null,null);
        List<TreeGridEntity> treeList = new ArrayList<>() ;
        for (OrganizeEntity item : organizeEntities)
        {
            TreeGridEntity tree = new TreeGridEntity();
            boolean hasChildren = organizeEntities.stream().anyMatch(x->x.getParentId().equals(item.getOrganizeId()));
            if(!hasChildren)
            {
//                hasChildren=departmentEntities.stream().anyMatch(x->x.getOrganizeId().equals(item.getOrganizeId()));
//               if(!hasChildren)  continue;
            }
            tree.setId(item.getOrganizeId());
            tree.setHasChildren(hasChildren);
            tree.setParentId(item.getParentId());
            tree.setExpanded(true);
            item.setEnCode("");
            item.setShortName ("");
            item.setNature( "");
            item.setManager ("");
            item.setOuterPhone ("");
            item.setInnerPhone("");
            item.setDescription ("");
            String entityJson = JSONUtils.beanToJson(item,"yyyy-MM-dd");
            StringBuilder itemJson = new StringBuilder(entityJson);
            itemJson=itemJson.insert(1, "\"departmentId\":\"" + item.getOrganizeId() + "\",");
            itemJson=itemJson.insert(1, "\"sort\":\"Organize\",");
            tree.setEntityJson(itemJson.toString());
            treeList.add(tree);
        }

        for(DepartmentEntity item:departmentEntities)
        {
            TreeGridEntity tree = new TreeGridEntity();
            boolean hasChildren = departmentEntities.stream().anyMatch(x->x.getParentId().equals(item.getDepartmentId()));
            tree.setId(item.getDepartmentId());
            tree.setParentId(item.getParentId().equals("0")?item.getOrganizeId():item.getParentId());
            tree.setExpanded(true);
            tree.setHasChildren(hasChildren);
            String entityJson = JSONUtils.beanToJson(item,"yyyy-MM-dd");
            StringBuilder itemJson = new StringBuilder(entityJson);
            itemJson=itemJson.insert(1, "\"sort\":\"Department\",");
            tree.setEntityJson(itemJson.toString());
            treeList.add(tree);
        }
        String jsonText= TreeGridJson.TreeJson(treeList);
        return  JSONObject.parse(jsonText);
    }


    /**
     * 列表
     * @param params
     * @return
     */
    @RequestMapping("/list")
    public Page<DepartmentEntity> list(@RequestBody Map<String, Object> params) {
        return departmentService.listDepartment(params);
    }

    /**
     * 新增
     * @param department
     * @return
     */
    @SysLog("新增部门信息表")
    @RequestMapping("/save")
    public R save(@RequestBody DepartmentEntity department) {
        return departmentService.saveDepartment(department);
    }

    /**
     * 根据id查询详情
     * @param id
     * @return
     */
    @RequestMapping("/info")
    public R getById(@RequestBody String id) {
        return departmentService.getDepartmentById(id);
    }

    /**
     * 修改
     * @param department
     * @return
     */
    @SysLog("修改部门信息表")
    @RequestMapping("/update")
    public R update(@RequestBody DepartmentEntity department) {
        return departmentService.updateDepartment(department);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @SysLog("删除部门信息表")
    @RequestMapping("/remove")
    public R batchRemove(@RequestBody String[] id) {
        return departmentService.batchRemove(id);
    }


}
